package com.zygh.questionnairesurvey.config;

import org.apache.ibatis.cache.Cache;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import org.springframework.util.DigestUtils;

/**
 * @author ms151
 * 自定义缓存实现
 */
public class RedisCache implements Cache {

    private final String id;


    public RedisCache(String id) {
        System.out.println("》》》》》》》》》》》》》》" + id);
        this.id = id;
    }

    @Override
    public String getId() {
        return this.id;
    }

    //缓存中放入值
    @Override
    public void putObject(Object key, Object value) {
//        System.out.println("key:" + key.toString());
//        System.out.println("value:" + value.toString());

        //存入redis
        getredisTemplate().opsForHash().put(id,getKeyToMD5(key.toString()), value);


    }

    @Override
    public Object getObject(Object key) {
        //获取数据
        return getredisTemplate().opsForHash().get(id, getKeyToMD5(key.toString()));
    }

    /**
     * 注意：这个方法为mybatis的保留方法，默认没有实现
     *
     * @param o
     * @return
     */
    @Override
    public Object removeObject(Object o) {
        return null;
    }

    @Override
    public void clear() {
        System.out.println("清空缓存！！！！~~~~");
        getredisTemplate().delete(id);

    }

    /**
     * 用来计算缓存数量
     * @return
     */
    @Override
    public int getSize() {

        return getredisTemplate().opsForHash().size(id).intValue();
    }

    //封装redisTemplate
    private RedisTemplate getredisTemplate(){
        //通过application工具类获取redisTemplate
        RedisTemplate redisTemplate = (RedisTemplate) ApplicationContextUtils.getBean("redisTemplate");
        redisTemplate.setKeySerializer(new StringRedisSerializer());
        redisTemplate.setHashKeySerializer(new StringRedisSerializer());
        return redisTemplate;
    }

    //封装一个对key进行MD5处理方法
    private String getKeyToMD5(String key){
        return DigestUtils.md5DigestAsHex(key.getBytes());
    }

}
